package com.leicx.guli.ware.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leicx.guli.common.constant.ParamConstant;
import com.leicx.guli.common.enums.PurchaseDetailStatusEnum;
import com.leicx.guli.common.enums.PurchaseStatusEnum;
import com.leicx.guli.common.utils.PageUtils;
import com.leicx.guli.common.utils.Query;
import com.leicx.guli.ware.dao.PurchaseDao;
import com.leicx.guli.ware.entity.PurchaseDetailEntity;
import com.leicx.guli.ware.entity.PurchaseEntity;
import com.leicx.guli.ware.service.PurchaseDetailService;
import com.leicx.guli.ware.service.PurchaseService;
import com.leicx.guli.ware.service.WareSkuService;
import com.leicx.guli.ware.vo.MergeVo;
import com.leicx.guli.ware.vo.PurchaseDoneVo;
import com.leicx.guli.ware.vo.PurchaseItemDoneVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    PurchaseDetailService purchaseDetailService;
    @Resource
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(ParamConstant.STATUS, 0)
                .or()
                .eq(ParamConstant.STATUS, 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (Objects.isNull(purchaseId)) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(PurchaseStatusEnum.CREATED.getCode());
            save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        List<Long> items = mergeVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(q -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(q);
                entity.setPurchaseId(finalPurchaseId);
                entity.setStatus(PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        updateById(purchaseEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void received(List<Long> ids) {
        Set<Long> purchaseIdSet = new HashSet<>();
        // 1.确认当前采购单是新建或已分配状态
        List<PurchaseEntity> collect = ids.stream().map(this::getById)
                .filter(q -> Objects.equals(q.getStatus(), PurchaseStatusEnum.CREATED.getCode())
                        || Objects.equals(q.getStatus(), PurchaseStatusEnum.ASSIGNED.getCode()))
                .peek(item -> {
                    purchaseIdSet.add(item.getId());
                    item.setStatus(PurchaseStatusEnum.RECEIVED.getCode());
                    item.setUpdateTime(new Date());
                }).collect(Collectors.toList());
        // 2.改变采购单状态
        updateBatchById(collect);
        // 3.改变采购需求的状态
        PurchaseDetailEntity entity = new PurchaseDetailEntity();
        entity.setStatus(PurchaseDetailStatusEnum.BUYING.getCode());
        purchaseDetailService.update(entity,
                new UpdateWrapper<PurchaseDetailEntity>().in(ParamConstant.PURCHASE_ID, purchaseIdSet));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long purchaseId = purchaseDoneVo.getId();
        // 1.改变采购需求状态
        boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            List<PurchaseDetailEntity> list = new ArrayList<>();
            for (PurchaseItemDoneVo item : items) {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                if (Objects.equals(item.getStatus(), PurchaseDetailStatusEnum.FAILURE.getCode())) {
                    entity.setStatus(item.getStatus());
                    flag = false;
                } else {
                    entity.setStatus(PurchaseDetailStatusEnum.FINISHED.getCode());
                    // 3.将成功采购的进行入库
                    PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                    wareSkuService.addStock(byId.getSkuId(), byId.getWareId(), byId.getSkuNum());
                }
                entity.setId(item.getItemId());
                list.add(entity);
            }
            purchaseDetailService.updateBatchById(list);
        }
        // 2.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? PurchaseStatusEnum.FINISHED.getCode() : PurchaseStatusEnum.HAS_ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        updateById(purchaseEntity);
    }

}